#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <cstring>
#include <cstdio>
//向管道内写数据
void childwrite(int wfd)
{
    // char buffer[1024];
    char c=0;
    int cnt=0;
    while(true)
    {
        // sleep(3);
        // snprintf(&c,sizeof(c),"i am child,pid:%d,cnt:%d",getpid(),cnt);
        write(wfd,&c,1);
        std::cout<<"cnt:"<<cnt++<<std::endl;
        // sleep(1);
        // break;
    }
}

//读数据
void fatherread(int rfd)
{
    char buffer[1024*2];
    while(true)
    {
        sleep(100);
        buffer[0]=0;
        ssize_t n=read(rfd,buffer,sizeof(buffer)-1);
        if(n>0)
        {
            buffer[n]=0;
            std::cout<<"child say:"<<buffer<<std::endl;
            // sleep(2);
        }
        else if(n==0)
        {
            std::cout<<"n :"<<n<<std::endl;
            std::cout<<"child process exit"<<std::endl;
            break;
        }
        else
        {
            break;
        }
        break;
    }
}

int main()
{
    int fd[2] = {0};//fd[0]:r,fd[1]w
    int n = pipe(fd);
    if (n < 0)
    {
        std::cout << "pipe error" << std::endl;
        return 1;
    }
    pid_t id=fork();
    //创建子进程
    if(id==0)
    {
        close(fd[0]);
        childwrite(fd[1]);
        close(fd[1]);
        exit(0);
    }

    //注释掉这里，运行程序无输出，说明父进程读取了子进程的信息才会输出
    //从而实现了管道    
    close(fd[1]);
    fatherread(fd[0]);
    close(fd[0]);
    int status = 0;
    int ret = waitpid(id, &status, 0); // 获取到子进程的退出信息吗！！！
    if(ret > 0)
    {
        printf("exit code: %d, exit signal: %d\n", (status>>8)&0xFF, status&0x7F);
        
        sleep(5);
    }
    
    return 0;
}